// pages/search/search.js
const service = require('../../utils/service.js')
const api = require('../../utils/util.js')
Page({
  data: {
    focus: true,
    searchKey: '',
    shopInfo: '',
    page: 1,
    goodsList: [],
    hasMoreData: true,
    valueText: ''
  },

  onLoad: function (options) {
    this.init()
  },
  init: function () {
    let shopInfo = wx.getStorageSync('shopInfo')
    this.setData({
      shopInfo: shopInfo
    })
  },

  // 获取搜索框内容
  getValue: function (e) {
    let search_key = e.detail.value
    this.setData({
      searchKey: search_key,
      page: 1,
      valueText: search_key
    })
  },

  eventTrigger: function () {
    this.setData({
      page: 1,
      goodsList: []
    })
    this.doSearch()
  },

  // 搜索商品
  doSearch: function () {
    let that = this
    let key = this.data.searchKey
    if (key == '' || key == null) {
      api.toast('请输入搜索内容')
      return
    }

    api.ajax(service.url('goodsSearch'), {
      unionid: that.data.shopInfo.unionid,
      shop_code: that.data.shopInfo.shop_code,
      page: that.data.page,
      keyword: key
    }, function (res) {
      console.log(res)
      if (res.code == 0) {
        if (res.data.length > 0) {
          for (var i = 0, len = res.data.length; i < len; i++) {
            that.data.goodsList.push(res.data[i])
          }
          that.setData({
            goodsList: that.data.goodsList,
            hasMoreData: true
          })
        } else {
          that.setData({
            hasMoreData: false
          })
        }
      } else {
        api.toast(res.message)
      }
    })
  },

  // 前往商品详情
  toGoodsDetail: function (e) {
    var goods_id = e.currentTarget.dataset.id
    if (!goods_id) {
      return
    }

    var yzc = e.currentTarget.dataset.yzc
    var audit = e.currentTarget.dataset.audit

    let url = `../goods_detail/goods_detail?goods_id=${goods_id}`
    if (yzc && audit == '1') {
      url = `../goods_detail/goods_detail?goods_id=${goods_id}&is_yzc=${yzc}`
    }
    wx.navigateTo({
      url: url,
    })
  },
  cancelSearch: function () {
    this.setData({
      focus: false,
      searchKey: '',
      page: 1,
      goodsList: [],
      valueText: ''
    })
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let type = this.data.navIndex
    let page = this.data.page += 1
    if (this.data.hasMoreData) {
      this.setData({
        page: page
      })
      this.doSearch()
    } else {
      api.toast('没有更多数据了')
    }
  }
})
